<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>

	<body>
		<h1>发布订阅模式例子-产品打折消息</h1>
		<button id="register">订阅</button>
		<button id="notify">通知</button>
		<input type="text" id="text" value="商品编号为B0001大减价" />
		<div class="content" id="content">

		</div>
		<script type="text/javascript">
			var content = document.querySelector("#content");
			var i = 1;
			const addLog = msg => {
				var p = document.createElement('p');
				p.innerHTML = i + ' : ' + msg;
				content.appendChild(p);
				i += 1;
			}

			const copyData = (source, target) => {
				var key = null;
				for(key in source) {
					if(source.hasOwnProperty(key)) {
						target[key] = source[key];
					}
				}
			}

			//info={id:'Z0001',name:'T01',price:'1.0'}
			var getProduct = info => {
				var fn = {
					register: function(client) {
						this.clientList.push(client)
					},
					unregister:function(client){
//						var tmp=this.clientList.find(c=>client.id===c.id);
//						this.clientList.remove(tmp);
					},
					notify: function(message) {
						this.clientList.forEach(client => {
							addLog('info from:{id:' + this.id + ',name:' + this.name + ',price:' + this.price + '}');
							client.receiveInfo(message);
						});
					}
				}
				var product = Object.create(fn);
				product.clientList = [];
				copyData(info, product);
				return product;
			}

			//info={id:'Z0001',name:'T01'}
			var getClient = info => {
				var fn = {
					receiveInfo: function(info) {
						addLog('info to : {id:' + this.id + ',name:' + this.name + '}');
						addLog('Info : '+info);
					}
				}
				var client = Object.create(fn);
				copyData(info, client);
				return client;
			}

			var book = getProduct({
				id: 'B0001',
				name: 'Great Wall',
				price: '$10.0'
			});
			document.getElementById('register').onclick = e => {
				book.register(getClient({
					id: 'C01',
					name: 'C01'
				}));
				book.register(getClient({
					id: 'C02',
					name: 'C02'
				}));
				book.register(getClient({
					id: 'C03',
					name: 'C03'
				}));
			}
			document.getElementById('notify').onclick = e => {
				var text=document.getElementById('text').value;
				book.notify(text);
			}
		</script>
	</body>

</html>